<template>
  <div class="audio-container" style="display:none;">
    <audio ref="notificationAudio" preload="auto">
      <source src="/sounds/notification.mp3" type="audio/mp3">
      您的浏览器不支持音频元素
    </audio>
    <audio ref="reminderAudio" preload="auto">
      <source src="/sounds/reminder.mp3" type="audio/mp3">
      您的浏览器不支持音频元素
    </audio>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

// 音频元素引用
const notificationAudio = ref(null)
const reminderAudio = ref(null)

// 导出播放方法给父组件使用
const playNotificationSound = () => {
  if (notificationAudio.value) {
    notificationAudio.value.currentTime = 0
    notificationAudio.value.volume = 0.7
    notificationAudio.value.play().catch(err => {
      console.error('播放通知音频失败:', err)
    })
  }
}

const playReminderSound = () => {
  if (reminderAudio.value) {
    reminderAudio.value.currentTime = 0
    reminderAudio.value.volume = 0.8
    reminderAudio.value.play().catch(err => {
      console.error('播放催单音频失败:', err)
    })
  }
}

// 预加载音频
onMounted(() => {
  console.log('音频组件已加载')
  
  // 监听用户首次交互，以绕过浏览器自动播放政策
  const userInteractionHandler = () => {
    // 尝试静音播放并立即暂停，以确保后续可以播放
    if (notificationAudio.value) {
      notificationAudio.value.volume = 0
      notificationAudio.value.play()
        .then(() => {
          notificationAudio.value.pause()
          notificationAudio.value.currentTime = 0
        })
        .catch(err => console.warn('音频预加载失败:', err))
    }
    
    if (reminderAudio.value) {
      reminderAudio.value.volume = 0
      reminderAudio.value.play()
        .then(() => {
          reminderAudio.value.pause()
          reminderAudio.value.currentTime = 0
        })
        .catch(err => console.warn('音频预加载失败:', err))
    }
    
    // 移除事件监听
    document.removeEventListener('click', userInteractionHandler)
    document.removeEventListener('keydown', userInteractionHandler)
  }
  
  // 添加事件监听
  document.addEventListener('click', userInteractionHandler)
  document.addEventListener('keydown', userInteractionHandler)
})

// 导出方法
defineExpose({
  playNotificationSound,
  playReminderSound
})
</script>

<style scoped>
.audio-container {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  opacity: 0;
}
</style> 